import 'dart:io';

import 'package:file_selector/file_selector.dart';
import 'package:flutter/material.dart';
import 'package:wechat_decode/components/unify_button.dart';

/// 解码页路径选择输入框
class DecodeInputField extends StatefulWidget {
  const DecodeInputField({
    super.key,
    required this.label,
    this.controller,
    this.validator,
    this.pathRequiredExist = false,
    this.enabled = true,
  });

  /// 字段名称
  final String label;

  /// 文本控制器
  final TextEditingController? controller;

  /// 字段校验
  final FormFieldValidator<String>? validator;

  /// 路径是否必须存在
  final bool pathRequiredExist;

  final bool enabled;

  @override
  State<DecodeInputField> createState() => _DecodeInputFieldState();
}

class _DecodeInputFieldState extends State<DecodeInputField> {
  TextEditingController? _controller;
  late TextEditingController _effectiveController;

  @override
  void initState() {
    _effectiveController = widget.controller ?? (_controller = TextEditingController());
    super.initState();
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.baseline,
      textBaseline: TextBaseline.alphabetic,
      children: [
        Text('${widget.label}：'),
        const SizedBox(width: 2),
        Expanded(
          child: TextFormField(
            enabled: widget.enabled,
            controller: _effectiveController,
            style: const TextStyle(fontSize: 15, height: 1.2),
            textAlignVertical: TextAlignVertical.bottom,
            decoration: const InputDecoration(
              border: OutlineInputBorder(),
              isDense: true,
              contentPadding: EdgeInsets.symmetric(vertical: 8, horizontal: 5),
            ),
            validator: (value) {
              if (value!.trim().isEmpty) {
                return '${widget.label}不能为空';
              }
              if (widget.pathRequiredExist && !Directory(value).existsSync()) {
                return '${widget.label}目录地址不存在';
              }
              return widget.validator?.call(value);
            },
          ),
        ),
        const SizedBox(width: 10),
        UnifyButton(
          text: '选择',
          enabled: widget.enabled,
          onPressed: () async {
            String? initialDirectory;
            if (Directory(_effectiveController.text).existsSync()) {
              initialDirectory = _effectiveController.text;
            }
            String? selectedDirectory = await getDirectoryPath(initialDirectory: initialDirectory);
            if (selectedDirectory == null) {
              debugPrint('取消选择');
            } else {
              _effectiveController.text = selectedDirectory;
            }
          },
        ),
      ],
    );
    ;
  }
}
